#include "StdAfx.h"
#include "FileWriter.h"

#ifdef _DEBUG
#include "crtdbg.h"
#endif

const char  CFileWriter::ceol[] = "\r\n";

bool CFileWriter::Open(const TCHAR* szFile, bool bUtf8)
{
  Close();

  if (szFile == NULL)
    return false;

  m_hFile = ::_tfopen(szFile, TEXT("wt"));
  if (m_hFile == NULL)
  {
    return false;
  }

  if (bUtf8)
    WriteUtf8();

  return true;
}

void CFileWriter::Close()
{
  if (m_hFile != NULL)
  {
    ::fclose(m_hFile);
    m_hFile = NULL;
  }
}

bool CFileWriter::Write(const TCHAR* s)
{
  if (m_hFile == NULL || s == NULL)
    return false;

  // convert from Unicode
  int size = ::WideCharToMultiByte(m_bUtf8 ? CP_UTF8 : CP_ACP, 0, s, -1, NULL, 0, 0, NULL);
  if (size <= 0)
    return false;

  char* buf = new char[size];
  if (!buf)
    return false;

  size = ::WideCharToMultiByte(m_bUtf8 ? CP_UTF8 : CP_ACP, 0, s, -1, buf, size, 0, NULL);
  if (size <= 0)
  {
    delete[] buf;
    return false;
  }

  int res = fputs(buf, m_hFile);
  delete[] buf;
  return res >= 0;
}

bool CFileWriter::WriteLine(const TCHAR* s)
{
  if (Write(s))
  {
    fputs(ceol, m_hFile);
    return true;
  }
  return false;
}

void CFileWriter::WriteUtf8()
{
  static BYTE bom[3]  = { 0xEF, 0xBB, 0xBF };
  static size_t len = sizeof(bom) / sizeof(BYTE);
  ::fwrite(bom, sizeof(BYTE), len, m_hFile);
}